package practise.alogrithm.hundredInterviewQuestions.convertToConcurrent;

import java.util.concurrent.*;

/**
 * Created by richard on 6/16/14.
 */
public class CalculateNumberOfPower extends RecursiveTask<Integer> {
    private Integer base, power;
    public CalculateNumberOfPower(Integer base, Integer power){
        this.base = base;
        this.power =power;
    }
    public Integer compute(){
        if(power==0){
            return 1;
        }
        CalculateNumberOfPower calculate = new CalculateNumberOfPower(base, power/2);
        calculate.fork();
        Integer result = calculate.join();
        if(power%2==0){
            return result*result;
        }
        else{
            if(power>0){
                return result*result*base;
            }
            else
                return result*result/base;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CalculateNumberOfPower calculateNumberOfPower = new CalculateNumberOfPower(2,2);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> futureTask = forkJoinPool.submit(calculateNumberOfPower);
        forkJoinPool.awaitQuiescence(1000, TimeUnit.SECONDS);
        System.out.println("result:"+futureTask.get());
    }
}
